const express = require('express');
const ejs = require('ejs');
const path = require('path');
const favicon = require('serve-favicon');
const log4js = require('log4js');
const bodyParser = require('body-parser');
const cookieParser = require('cookie-parser');
const session = require('express-session');
const connectRedis = require('connect-redis');
const cors = require('cors');
const proxy = require('http-proxy-middleware');

const config = require('./config');
const mkdirs = require('./server/common/mkdirs');
const logger = require('./server/common/logger');
const tools = require('./server/middlewares/tools');
const routes = require('./server/routes');
const webpack = require('webpack');
const webpackDevMiddleware = require('webpack-dev-middleware');
const webpackConfig = require('./build/webpack.dev.conf.js');

const app = express();

//开发环境下，运行wenpack-dev
if (app.get('env') == "development") {
    const compiler = webpack(webpackConfig);
    app.use(webpackDevMiddleware(compiler, {
        publicPath: 'http://127.0.0.1:8080/'
    }));
}

//代理
app.use(/\/api/, proxy({
    //target: 'http://39.106.34.181:8080/monitor',
    target: 'http://127.0.0.1:8080/cumtb',
    changeOrigoin: true,
    pathRewrite: { '^/api': '/' }
}));

// 判断文件夹是否存在, 若不存在则创建之
const mkdirsSync = mkdirs.mkdirsSync;
mkdirsSync(config.upload.tmp);
mkdirsSync(config.upload.path);

// 视图引擎
app.engine('.html', ejs.__express);
app.set('view engine', 'html');
app.set('views', path.join(__dirname, 'front'));

app.use(favicon(__dirname + '/server/public/favicon.ico'));
app.use(log4js.connectLogger(logger('normal'), { level: 'auto', format: ':method :url :status' }));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use('/', express.static(path.join(__dirname, 'front/dist')));
app.use('/public', express.static(path.join(__dirname, 'server/public')));

app.use(cookieParser(config.secret));

//set session.
//const RedisStore = connectRedis(session);
app.use(session({
    // store: new RedisStore({
    //     host: '127.0.0.1',
    //     port: '6379',
    //     ttl: 60 * 60
    // }),
    cookie: {
        maxAge: 3600000,
    },
    resave: false,
    saveUninitialized: true,
    secret: config.secret
}));

app.use(cors());

app.get('/', function(req, res, next) {
    res.render('./client/index');
});

app.use(/\/view/, tools);

// 加载路由
routes(app);

// catch 404 and forward to error handler
app.use((req, res, next) => {
    const err = new Error('Not Found');
    err.status = 404
    next(err)
});
// error handlers

// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
    app.use((err, req, res, next) => {
        console.log(err)
        res.status(err.status || 500)
        res.render('error', {
            layout: false,
            message: err.message,
            error: err
        })
    })
};

// production error handler
// no stacktraces leaked to user
app.use((err, req, res, next) => {
    res.status(err.status || 500)
    res.render('error', {
        layout: false,
        message: err.message,
        error: err
    })
});

module.exports = app